package com.tzxs.pay.main.bill;

import android.app.Dialog;
import android.arch.lifecycle.Observer;
import android.arch.lifecycle.ViewModelProviders;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.baiiu.filter.adapter.MenuAdapter;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.view.TimePickerView;
import com.tzxs.pay.BR;
import com.tzxs.pay.R;
import com.tzxs.pay.databinding.FragmentBillsBinding;
import com.tzxs.pay.databinding.ItemBillsBinding;
import com.tzxs.pay.main.BaseFragment;
import com.tzxs.pay.main.bill.detail.CollAndInstallDetailActivity;
import com.tzxs.pay.main.bill.model.CollectionBillBean;
import com.tzxs.pay.main.bill.viewmodel.BillViewModel;
import com.tzxs.pay.util.IAdapter;
import com.tzxs.pay.util.IHolder;
import com.tzxs.pay.util.ISharedPreference;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

//账单
public class BillsFragment extends BaseFragment<FragmentBillsBinding> implements IAdapter.ItemNavigator<CollectionBillBean> {
    private static final String TAG = BillsFragment.class.getSimpleName();
    private BillViewModel model;
    private int page = 1;
    private int timeType = 1;//时间类型  默认1  今天的
    private List<View> contentView;//下拉 筛选的view
    private boolean iscreated = false;
    private View time, payTye;
    private String payTypeStr = "不限";//支付类型
    private TextView timeAll;//不限时间
    private TextView today;//今天
    private TextView yesterday;//昨天
    private TextView thisWeek;//本周
    private TextView thisMonth;//本月
    private TextView lastMonth;//上月
    private TextView startTimeView;//开始时间
    private TextView endTimeView;//结束时间
    private String[] titles = {"天择可付-总部", "今天", "不限"};
    private String startTimeStr = "";//开始的时间
    private String endTimeStr = "";//结束的时间

    private TextView allType;//不限
    private TextView alipay;//支付宝支付
    private TextView wx;//微信支付
    private TextView bank;//银行卡支付

    @Override
    public int getContentLayoutId() {
        return R.layout.fragment_bills;
    }

    @Override
    protected void viewCreate(Bundle savedInstanceState) {
        iscreated = true;
        model = ViewModelProviders.of(this).get(BillViewModel.class);
        binding.setViewModel(model);
        setUserVisibleHint(true);
        Log.d(TAG, "viewCreate:用户名 :  " + ISharedPreference.getInstance(getActivity().getApplication()).getUserName());
        //门店名称

        initContentView();//初始化下拉菜单的view
        binding.fixedTabIndicator.setBackgroundResource(R.drawable.bills_condition_bg);

        //给DropMenuLayout定义下拉框
        binding.dropDownMenu.setMenuAdapter(new MenuAdapter() {
            @Override
            public int getMenuCount() {
                //数量
                return 3;
            }

            @Override
            public String getMenuTitle(int i) {
                //默认的标题
                return titles[i];//我选中改标题呢
            }

            @Override
            public int getBottomMargin(int i) {
                //蒙层距离底部的位置,默认0
                return 0;
            }

            @Override
            public View getView(int i, FrameLayout frameLayout) {
                //返回相应的View//
                return contentView.get(i);
            }
        });

//        binding.address.setText(ISharedPreference.getInstance(getActivity().getApplication()).getUserName());


        //搜索
        binding.search.setOnClickListener(v -> {

            Intent intent = new Intent(getContext(), BillSearchActivity.class);
            startActivity(intent);

        });
        //设置recyclerview 的布局管理器和数据
        binding.billsRec.setLayoutManager(new LinearLayoutManager(getContext()));

        binding.billsRec.setAdapter(new IAdapter<CollectionBillBean, ItemBillsBinding>() {

            @Override
            protected int getLayoutId(int viewType) {
                return R.layout.item_bills;
            }

            //判断两个item的订单号相同
            @Override
            public boolean areItemsTheSame(List<CollectionBillBean> oldData, List<CollectionBillBean> data, int oldItemPosition, int newItemPosition) {
                return oldData.get(oldItemPosition).getOut_trade_no().equals(data.get(newItemPosition).getOut_trade_no());
            }

            //判断两个订单的状态是否相等
            @Override
            public boolean areContentsTheSame(List<CollectionBillBean> oldData, List<CollectionBillBean> data, int oldItemPosition, int newItemPosition) {
                return oldData.get(oldItemPosition).getPay_status() == (data.get(newItemPosition).getPay_status());
            }

            @Override
            protected void convertListener(@NonNull ItemBillsBinding binding) {
                binding.setNavigator(BillsFragment.this);
            }

            @Override
            protected int getDataBRId(int itemViewType) {
                return BR.item;
            }

            @Override
            public void onBindViewHolder(IHolder<ItemBillsBinding> holder, int position) {
                super.onBindViewHolder(holder, position);
                //支付方式
                switch (getData().get(position).getPay_type()) {
                    case "weixin":
                        holder.binding.payTypeIc.setImageResource(R.drawable.ic_wechat);
                        break;
                    case "alipay":
                        holder.binding.payTypeIc.setImageResource(R.drawable.ic_alipay);
                        break;
                    default:
                        holder.binding.payTypeIc.setImageResource(R.drawable.ic_unionpay);
                        break;
                }
            }
        });


        //重置搜索条件
        binding.reset.setOnClickListener(v -> resetCondiction());
        //监听提示
        model.snackbarText.observe(this, s -> {
            if (s != null) {
                Toast.makeText(getContext(), s, Toast.LENGTH_SHORT).show();
            }
        });

        //刷新数据
        binding.content.setOnRefreshListener(refreshLayout -> {
            //下拉刷新重置page
            page = 1;
            //重新加载数据
            //延时2s刷新数据

            model.getCoInResultBills(null, getPayTypeStr(payTypeStr), null, timeType, page, 10,
                    null, startTimeStr, endTimeStr, () -> {
//                        binding.billsRec.scrollToPosition(0);
                        binding.billsRec.smoothScrollToPosition(0);

                    });
            refreshLayout.finishRefresh(1000);//不管有没有获取成功 都结束
        });


        //加载更多
        binding.content.setOnLoadMoreListener(refreshLayout -> {
            ++page;
            Log.d(TAG, "viewCreate: 此时的page:" + page);
            model.getCoInResultBills(null, getPayTypeStr(payTypeStr), null, timeType, page, 10,
                    null, startTimeStr, endTimeStr, () -> {

                    });
            refreshLayout.finishLoadMore(1000);
        });

    }

    //重置所有条件
    private void resetCondiction() {
        timeType = 1;
        startTimeStr = "";
        endTimeStr = "";
        payTypeStr = "不限";
        startTimeView.setText("");
        endTimeView.setText("");
        clearTimeStatus(timeAll, today, yesterday, thisWeek, thisMonth, lastMonth);
        clearPayType(allType, alipay, wx, bank);
        today.setSelected(true);
        allType.setSelected(true);
        binding.dropDownMenu.setPositionIndicatorText(1, "今天", 14);
        binding.dropDownMenu.setPositionIndicatorText(2, "不限", 14);
        binding.dropDownMenu.close();
        getData(getPayTypeStr(payTypeStr), timeType, startTimeStr, endTimeStr);

    }

    //初始化显示pop筛选
    private void initContentView() {
        contentView = new ArrayList<>();
        View name = getLayoutInflater().inflate(R.layout.bills_name, null);
        TextView name1 = name.findViewById(R.id.name_1);
        name1.setText(ISharedPreference.getInstance(Objects.requireNonNull(getActivity()).getApplication()).getUserName());
        name1.setSelected(true);
        //时间
        time = getLayoutInflater().inflate(R.layout.pop_order_time, null);
        timeAll = time.findViewById(R.id.fast_choose_all);
        today = time.findViewById(R.id.fast_choose_today);
        yesterday = time.findViewById(R.id.fast_choose_yesterday);
        thisWeek = time.findViewById(R.id.fast_choose_this_week);
        thisMonth = time.findViewById(R.id.fast_choose_this_month);
        lastMonth = time.findViewById(R.id.fast_choose_last_month);
        startTimeView = time.findViewById(R.id.choose_conditions_start);
        endTimeView = time.findViewById(R.id.choose_conditions_end);
        TextView commitTime = time.findViewById(R.id.commit_sure);
        today.setSelected(true);
        //支付类型
        payTye = getLayoutInflater().inflate(R.layout.pop_pay_type, null);
        allType = payTye.findViewById(R.id.pay_type_all);
        alipay = payTye.findViewById(R.id.pay_type_alipay);
        wx = payTye.findViewById(R.id.pay_type_wx);
        bank = payTye.findViewById(R.id.pay_type_bank);
        allType.setSelected(true);

        //不限
        timeAll.setOnClickListener(v -> {
            clearTimeStatus(timeAll, today, yesterday, thisWeek, thisMonth, lastMonth);
            startTimeStr = "";
            endTimeStr = "";
            startTimeView.setText("");
            endTimeView.setText("");
            timeType = -1;
            timeAll.setSelected(true);
            binding.dropDownMenu.setPositionIndicatorText(1, timeAll.getText().toString(), 14);//这个就是你选完之后改标题的方法
            binding.dropDownMenu.close();
            getData(getPayTypeStr(payTypeStr), timeType, startTimeStr, endTimeStr);
        });
        //今天
        today.setOnClickListener(v -> {
            clearTimeStatus(timeAll, today, yesterday, thisWeek, thisMonth, lastMonth);
            startTimeStr = "";
            endTimeStr = "";
            timeType = 1;
            startTimeView.setText("");
            endTimeView.setText("");
            today.setSelected(true);
            binding.dropDownMenu.setPositionIndicatorText(1, today.getText().toString(), 14);
            binding.dropDownMenu.close();
            getData(getPayTypeStr(payTypeStr), timeType, startTimeStr, endTimeStr);
        });
        //昨天
        yesterday.setOnClickListener(v -> {
            clearTimeStatus(timeAll, today, yesterday, thisWeek, thisMonth, lastMonth);
            startTimeStr = "";
            endTimeStr = "";
            yesterday.setSelected(true);
            timeType = 2;
            startTimeView.setText("");
            endTimeView.setText("");
            binding.dropDownMenu.setPositionIndicatorText(1, yesterday.getText().toString(), 14);
            binding.dropDownMenu.close();
            getData(getPayTypeStr(payTypeStr), timeType, startTimeStr, endTimeStr);
        });
        //本周
        thisWeek.setOnClickListener(v -> {
            clearTimeStatus(timeAll, today, yesterday, thisWeek, thisMonth, lastMonth);
            startTimeStr = "";
            endTimeStr = "";
            timeType = 3;
            startTimeView.setText("");
            endTimeView.setText("");
            thisWeek.setSelected(true);
            binding.dropDownMenu.setPositionIndicatorText(1, thisWeek.getText().toString(), 14);
            binding.dropDownMenu.close();
            getData(getPayTypeStr(payTypeStr), timeType, startTimeStr, endTimeStr);
        });
        //本月
        thisMonth.setOnClickListener(v -> {
            clearTimeStatus(timeAll, today, yesterday, thisWeek, thisMonth, lastMonth);
            startTimeStr = "";
            endTimeStr = "";
            timeType = 4;
            startTimeView.setText("");
            endTimeView.setText("");
            thisMonth.setSelected(true);
            binding.dropDownMenu.setPositionIndicatorText(1, thisMonth.getText().toString(), 14);
            binding.dropDownMenu.close();
            getData(getPayTypeStr(payTypeStr), timeType, startTimeStr, endTimeStr);
        });
        //上月
        lastMonth.setOnClickListener(v -> {
            clearTimeStatus(timeAll, today, yesterday, thisWeek, thisMonth, lastMonth);
            startTimeStr = "";
            endTimeStr = "";
            timeType = 5;
            startTimeView.setText("");
            endTimeView.setText("");
            lastMonth.setSelected(true);
            binding.dropDownMenu.setPositionIndicatorText(1, lastMonth.getText().toString(), 14);
            binding.dropDownMenu.close();
            getData(getPayTypeStr(payTypeStr), timeType, startTimeStr, endTimeStr);
        });

        //开始时间
        startTimeView.setOnClickListener(v -> {
            timeType = -1;
            chooseTime(startTimeView, 0);
        });
        //结束时间
        endTimeView.setOnClickListener(v -> {
            timeType = -1;
            chooseTime(endTimeView, 1);
        });
        //提交选中的时间
        commitTime.setOnClickListener(v -> {
            if (TextUtils.isEmpty(startTimeStr) || TextUtils.isEmpty(endTimeStr)) {
                Toast.makeText(getContext(), "请输入完整时间段", Toast.LENGTH_SHORT).show();
                return;
            }
            if (timeJudge(startTimeView.getText().toString()) > timeJudge(endTimeView.getText().toString())) {
                Toast.makeText(getContext(), "结束时间不能小于开始时间", Toast.LENGTH_SHORT).show();
                return;
            }
            clearTimeStatus(timeAll, today, yesterday, thisWeek, thisMonth, lastMonth);
            binding.dropDownMenu.setPositionIndicatorText(1, startTimeStr + "\n" + "至\n" + endTimeStr, 10);
            binding.dropDownMenu.close();
            getData(getPayTypeStr(payTypeStr), timeType, startTimeStr, endTimeStr);

        });

        //所有支付类型
        allType.setOnClickListener(v -> {
            clearPayType(allType, alipay, wx, bank);
            allType.setSelected(true);
            payTypeStr = "不限";
            binding.dropDownMenu.setPositionIndicatorText(2, allType.getText().toString(), 14);
            binding.dropDownMenu.close();
            getData(getPayTypeStr(payTypeStr), timeType, startTimeStr, endTimeStr);
        });
        //支付宝
        alipay.setOnClickListener(v -> {
            clearPayType(allType, alipay, wx, bank);
            alipay.setSelected(true);
            payTypeStr = "支付宝";
            binding.dropDownMenu.setPositionIndicatorText(2, alipay.getText().toString(), 14);
            binding.dropDownMenu.close();
            getData(getPayTypeStr(payTypeStr), timeType, startTimeStr, endTimeStr);
        });
        //微信
        wx.setOnClickListener(v -> {
            clearPayType(allType, alipay, wx, bank);
            wx.setSelected(true);
            payTypeStr = "微信";
            binding.dropDownMenu.setPositionIndicatorText(2, wx.getText().toString(), 14);
            binding.dropDownMenu.close();
            getData(getPayTypeStr(payTypeStr), timeType, startTimeStr, endTimeStr);
        });
        //银行卡
        bank.setOnClickListener(v -> {
            clearPayType(allType, alipay, wx, bank);
            bank.setSelected(true);
            payTypeStr = "银联";
            binding.dropDownMenu.setPositionIndicatorText(2, bank.getText().toString(), 14);
            binding.dropDownMenu.close();
            getData(getPayTypeStr(payTypeStr), timeType, startTimeStr, endTimeStr);
        });
        contentView.add(name);
        contentView.add(time);
        contentView.add(payTye);

    }

    //清除支付类型选中状态
    private void clearPayType(TextView all, TextView alipay, TextView wx, TextView bank) {
        all.setSelected(false);
        alipay.setSelected(false);
        wx.setSelected(false);
        bank.setSelected(false);
    }

    //清除时间选中状态
    private void clearTimeStatus(TextView timeAll, TextView today, TextView yesterday,
                                 TextView thisWeek, TextView thisMonth, TextView lastMonth) {
        timeAll.setSelected(false);
        today.setSelected(false);
        yesterday.setSelected(false);
        thisWeek.setSelected(false);
        thisMonth.setSelected(false);
        lastMonth.setSelected(false);

    }

    //按照搜索条件搜索
    private void getData(String payTypeStr, int timeType, String startTime, String endTime) {

        model.getCoInResultBills(null, getPayTypeStr(payTypeStr), null, timeType, 1, 10,
                null, startTime, endTime, () -> {


                });
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        if (isVisibleToUser && iscreated) {
            model.getCoInResultBills(null, getPayTypeStr(payTypeStr), null, timeType, 1, 10,
                    null, startTimeStr, endTimeStr, () -> {

                    });
        }
    }

    @Override
    public void itemClick(CollectionBillBean item) {
        Intent intent = new Intent(getContext(), CollAndInstallDetailActivity.class);
        intent.putExtra("orderId", item.getOut_trade_no());
        startActivity(intent);
    }


    //获取支付类型对应的数字字符串
    private String getPayTypeStr(String type) {
        switch (type) {
            case "支付宝":
                payTypeStr = "alipay";
                break;
            case "微信":
                payTypeStr = "weixin";
                break;
            case "银联":
                payTypeStr = "SfBank";
                break;
            case "不限":
                payTypeStr = "all";
                break;
        }
        return payTypeStr;
    }

    private String getTime(Date date) {//可根据需要自行截取数据显示
        Log.d("getTime()", "choice date millis: " + date.getTime());
        SimpleDateFormat format = (SimpleDateFormat) SimpleDateFormat.getDateInstance();
        format.applyPattern("yyyy-MM-dd HH:mm:ss");
        return format.format(date);
    }

    /**
     * 选择时间
     *
     * @param id 控件id
     */
    private void chooseTime(TextView timeView, int id) {

        Log.d(TAG, "chooseTime: 选择时间:");
        //时间选择器
        TimePickerView pvTime = new TimePickerBuilder(getContext(), (date, v) -> {
            timeView.setText(getTime(date));
            switch (id) {
                case 0:
                    startTimeStr = getTime(date);
                    break;
                case 1:
                    endTimeStr = getTime(date);
                    break;
            }

        })
                .setType(new boolean[]{true, true, true, true, true, true})
                .isDialog(true)
                .build();


        Dialog mDialog = pvTime.getDialog();
        if (mDialog != null) {

            FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT,
                    Gravity.BOTTOM);

            params.leftMargin = 0;
            params.rightMargin = 0;
            pvTime.getDialogContainerLayout().setLayoutParams(params);

            Window dialogWindow = mDialog.getWindow();
            if (dialogWindow != null) {
                dialogWindow.setWindowAnimations(com.bigkoo.pickerview.R.style.picker_view_slide_anim);//修改动画样式
                dialogWindow.setGravity(Gravity.BOTTOM);//改成Bottom,底部显示
            }
            mDialog.show();
        }
    }


    //判断时间段选择
    private long timeJudge(String time) {
        SimpleDateFormat simpleDateFormat = (SimpleDateFormat) SimpleDateFormat.getDateInstance();
        simpleDateFormat.applyPattern("yyyy-MM-dd HH:mm:ss");
        try {
            Date date = simpleDateFormat.parse(time);
            return date.getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }

        return 0;
    }

}
